package example1;

import org.apache.commons.collections4.ListUtils;
import org.apache.commons.io.FileUtils;

import java.io.IOException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class HexUtil {

    private static final String FILE_ENCODING = "GBK";

    /**
     * 写入16进制字符数组到文件
     *
     * @param hexArray 16进制字符数组
     * @param names    文件名
     * @throws IOException
     */
    public static void writeHexArrToFile(String[] hexArray, final String... names) throws IOException {
        String data = HexUtil.hexArrToString(hexArray);
        FileUtils.writeStringToFile(FileUtils.getFile(names), data, FILE_ENCODING);
    }

    /**
     * 从文件中读取16进制字符串转换成字符数组
     *
     * @param names 文件名
     * @return 16进制字符数组
     * @throws IOException
     */
    public static String[] readFileToHexArr(final String... names) throws IOException {
        List<String> readLines = FileUtils.readLines(FileUtils.getFile(names), FILE_ENCODING);
        List<String> allHexList = new LinkedList<>();
        for (String line : readLines) allHexList.addAll(Arrays.asList(line.split(" ")));
        String[] objects = (String[]) allHexList.toArray();
        return objects;
    }

    /**
     * 16进制字符数组转换字符
     *
     * @param hxArr 16进制字符数组
     * @return
     */
    public static String hexArrToString(String[] hxArr) {
        List<String> stringList = Arrays.asList(hxArr);
        List<List<String>> partition = ListUtils.partition(stringList, 16);
        List<String> lineList = new LinkedList<>();
        for (List<String> list : partition) lineList.add(String.join("", list));
        String join = String.join("\n", lineList);
        return join;
    }

    /**
     * 16进制字符数组转换byte数组
     *
     * @param hxArr 16进制字符数组
     * @return byte数组
     */
    public static byte[] hexToByteArray(String[] hxArr) {
        byte[] byteArr = new byte[hxArr.length];
        for (int i = 0; i < hxArr.length; i++) {
            byteArr[i] = ((byte) Integer.parseInt(hxArr[i], 16));
        }
        return byteArr;
    }

    /**
     * bytes数组转换16进制字符数组
     *
     * @param bytes bytes数组
     * @return 16进制字符数组
     */
    public static String[] byteToHexStringArray(byte[] bytes) {
        String[] hexArr = new String[bytes.length];
        for (int i = 0; i < bytes.length; i++) {
            hexArr[i] = String.format("%02X", bytes[i]);
        }
        return hexArr;
    }

}
